package com.ksd.pug.clound.service;

import com.ksd.pug.clound.pojo.SysUser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/3$ 19:32$
 */
@Service
@Slf4j
public class UserServiceFuture {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCollapser(
            batchMethod = "batchSysUser",
            scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
            collapserProperties = {
                    // 请求实际间隔在10ms之内的请求会被合并到一个请求中。默认是 10毫秒
                    @HystrixProperty(name = HystrixPropertiesManager.TIMER_DELAY_IN_MILLISECONDS, value = "20"),
                    // 设置触发批量处理执行之前，在批处理中允许的最大请求数量。
                    @HystrixProperty(name = HystrixPropertiesManager.MAX_REQUESTS_IN_BATCH, value = "200"),
            }
    )
    public Future<SysUser> getSysuser(Long id) {
        System.out.println("===================" + id + "================");
        return null;
    }

    /**
     * 批处理的方式
     *
     * @param ids
     * @return
     */
    @HystrixCommand
    public List<SysUser> batchSysUser(List<Long> ids) {
        log.info("请求合并的ids是:{}", ids);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < ids.size(); i++) {
            if (i == ids.size() - 1) {
                stringBuilder.append(ids.get(i));
            } else {
                stringBuilder.append(ids.get(i) + ",");
            }
        }
        SysUser[] sysUsers = restTemplate.getForObject("http://pug-hystrix-user-service/user/batch?userIds=" + stringBuilder.toString(), SysUser[].class);
        return Arrays.asList(sysUsers);
    }

}
